import { Blog } from "../model/Blog.js"
import { Op } from "sequelize";
import url from 'url'

//定义路由的具体操作

//查询所有博客
async function blogsList(ctx) {



    // let keyWord = url.parse(ctx.url, true).query['kewWord'] || null;
    // let keyWord = url.parse(ctx.url, true).query.kewWord || null;
    let keyWord = ctx.request.query.kewWord || null;
    console.log(keyWord);


    let blogs;
    if (keyWord) {
        blogs = await Blog.findAll({
            where: {
                [Op.or]: [
                    {
                        name: {
                            [Op.like]: `%${keyWord}%`
                        }
                    },
                    {
                        address: {
                            [Op.like]: `%${keyWord}%`
                        }
                    }
                ]
            }
        })
        return ctx.body = {
            code: 200,
            msg: "搜索博客列表成功",
            data: blogs
        };
    } else {
        blogs = await Blog.findAll()
        if (!blogs.length) {
            return ctx.body = {
                code: 400,
                msg: "请求博客列表失败",
                data: null
            };
        }
        ctx.body = {
            code: 200,
            msg: "请求博客列表成功",
            data: blogs
        };
    }


}

async function blogById(ctx) {
    let id = ctx.params.id;
    let blog = await Blog.findByPk(id);
    if (!blog) {
        return ctx.body = "暂无此人"
    }
    ctx.body = {
        code: 200,
        msg: "根据id查询博客成功",
        data:blog
    };
}

async function delById(ctx, next) {
    let id = ctx.params.id;
    let boolean = await Blog.destroy({
        where: {
            id: id
        }
    });
    if (boolean != 1) {
        ctx.body = "删除失败"
    }
    ctx.body = "删除成功"
}

async function addBlog(ctx, next) {
    let blog = ctx.request.body;
    await Blog.create(blog);
    console.log(blog);
    ctx.body = '新增博客'
}

async function editBlog(ctx, next) {
    let id = ctx.params.id;
    let blog = await Blog.findByPk(id)
    let editBlog = ctx.request.body;
    let newBlog = await Blog.update(editBlog, {
        where: {
            id: id
        }
    });
    ctx.body = editBlog;
}

//暴露路由
export const blogs = {
    'GET /blogs': blogsList,
    'GET /blog/:id': blogById,
    'DELETE /blog/:id': delById,
    'POST /blog': addBlog,
    'PUT /blog/:id': editBlog
}